package com.brotherly.mpgp.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;

public class GameManagerUtil {

    public interface PackageInfoLoadListener {
        public void onPackageInfoLoadFinished(Map<String, ApplicationInfo> infos);
    }

    public final static HashMap<String, ApplicationInfo> ApplicationInfos = new HashMap<String, ApplicationInfo>();

    public final static List<JSONObject> ArticlesList = new ArrayList<JSONObject>();

    public static int ArticlesTotalCount = 0;

    /**
     * key-游戏包名，value-游戏相关文章
     */
    public final static Map<String, JSONObject> GameArticles = new HashMap<String, JSONObject>();

    public final static List<JSONObject> GameInfos = new LinkedList<JSONObject>();

    public final static List<String> GameRankNames = new ArrayList<String>();

    public final static List<JSONObject> GameRecommends = new LinkedList<JSONObject>();

    public static int GameRecommendsTotalCount = 0;

    public final static List<String> GameTags = new ArrayList<String>();

    public final static List<JSONObject> MarrowsList = new ArrayList<JSONObject>();

    public static boolean isInstalledGame(int id)
    {
        for (JSONObject game : GameInfos)
        {
            if (game.optInt("id", 0) == id)
            {
                return true;
            }
        }
        return false;
    }

    public static void InitAppData(Context context, JSONObject data)
    {
        try
        {
            JSONArray gameInfos = data.getJSONObject("identifier").getJSONArray("body");
            updateGameInfos(context, gameInfos);

            JSONArray tags = data.getJSONObject("tags").getJSONArray("body");
            updateGameTags(context, tags);

            JSONObject recommends = data.getJSONObject("ranks");
            updateGameRankRecommends(recommends, true);

            JSONObject articlesJson = data.getJSONObject("articles");
            updateArticleList(articlesJson, true);

            if (data.has("marrows"))
            {
                JSONObject marrowsJson = data.getJSONObject("marrows");
                JSONArray marrows = marrowsJson.getJSONArray("body");
                updateMarrows(context, marrows);
            } else
            {
                MarrowsList.clear();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void loadPackageInfo(Context context, PackageInfoLoadListener listener)
    {
        ApplicationInfos.clear();
        PackageManager packageManager = context.getPackageManager();
        List<ApplicationInfo> applicationInfos = packageManager.getInstalledApplications(0);
        int count = applicationInfos.size();
        for (int i = 0; i < count; i++)
        {
            ApplicationInfo applicationInfo = applicationInfos.get(i);
            String packageName = applicationInfo.packageName;// 包名
            ApplicationInfos.put(packageName, applicationInfo);
        }
        if (listener != null)
        {
            listener.onPackageInfoLoadFinished(ApplicationInfos);
        }
    }

    public static void updateArticleList(JSONObject json, boolean isClearOld)
    {
        if (isClearOld)
        {
            ArticlesList.clear();
        }
        try
        {
            JSONArray articles = json.getJSONArray("body");
            ArticlesTotalCount = json.has("count") ? json.getInt("count") : 0;
            for (int i = 0; i < articles.length(); i++)
            {
                ArticlesList.add(articles.getJSONObject(i));
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void updateGameArticles(Context context, String packageName, JSONObject articles)
    {
        JSONObject existArticlesInfo = GameArticles.get(packageName);
        try
        {
            JSONArray existArticles = null;
            if (existArticlesInfo == null)
            {
                existArticles = new JSONArray();
                existArticlesInfo = new JSONObject();
                existArticlesInfo.put("articles", existArticles);
                existArticlesInfo.put("count", 0);
                GameArticles.put(packageName, existArticlesInfo);
            } else
            {
                existArticles = existArticlesInfo.getJSONArray("articles");
            }
            JSONArray newArticles = articles.getJSONArray("body");
            for (int i = 0; i < newArticles.length(); i++)
            {
                JSONObject newarticle = newArticles.getJSONObject(i);
                String newid = newarticle.getString("id");
                boolean isnew = true;
                for (int j = 0; j < existArticles.length(); j++)
                {
                    JSONObject existarticle = existArticles.getJSONObject(j);
                    String existid = existarticle.getString("id");
                    if (existid.equals(newid))
                    {
                        isnew = false;
                        break;
                    }
                }
                if (isnew)
                {
                    existArticles.put(newarticle);
                }
            }
            existArticlesInfo.put("count", articles.getInt("count"));
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }

    }

    public static void updateGameInfos(Context context, JSONArray remoteGameInfos)
    {
        GameInfos.clear();
        // PackageManager packageManager = context.getPackageManager();
        for (Entry<String, ApplicationInfo> entry : ApplicationInfos.entrySet())
        {
            String packageName = entry.getKey();
            // String packageLabel =
            // packageManager.getApplicationLabel(entry.getValue()).toString();//
            // 获取label
            for (int i = 0; i < remoteGameInfos.length(); i++)
            {
                try
                {
                    JSONObject gameinfo = remoteGameInfos.getJSONObject(i);
                    if (gameinfo.has("identifiers"))
                    {
                        JSONArray packageNames = gameinfo.getJSONArray("identifiers");
                        // String name = gameinfo.getString("name");
                        for (int pindex = 0; packageNames != null && pindex < packageNames.length(); pindex++)
                        {
                            if (packageName.equals(packageNames.getString(pindex).trim()))
                            {
                                gameinfo.put("packageName", packageName);
                                GameInfos.add(gameinfo);
                                break;
                            }
                        }
                    }
                }
                catch (JSONException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void updateGameRankRecommends(JSONObject recommend, boolean isClearHistory)
    {
        if (isClearHistory)
        {
            GameRecommends.clear();
        }
        try
        {
            JSONArray recommends = recommend.getJSONArray("body");
            for (int i = 0; i < recommends.length(); i++)
            {
                GameRecommends.add(recommends.getJSONObject(i));
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void updateGameRecommends(Context context, JSONObject recommend, boolean isClearHistory)
    {
        try
        {
            JSONArray recommends = recommend.getJSONArray("body");
            GameRecommendsTotalCount = recommend.getInt("count");
            if (isClearHistory)
            {
                GameRecommends.clear();
            }
            for (int i = 0; i < recommends.length(); i++)
            {
                GameRecommends.add(recommends.getJSONObject(i));
            }
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
    }

    public static void updateGameTags(Context context, JSONArray tagArray)
    {
        GameTags.clear();
        for (int i = 0; i < tagArray.length(); i++)
        {
            try
            {
                GameTags.add(tagArray.getString(i));
            }
            catch (JSONException e)
            {
                e.printStackTrace();
            }
        }
    }

    public static void updateMarrows(Context context, JSONArray marrows)
    {
        MarrowsList.clear();
        for (int i = 0; i < marrows.length(); i++)
        {
            try
            {
                JSONObject marrow = marrows.getJSONObject(i);
                if (marrow.getBoolean("hasPoster"))
                {
                    MarrowsList.add(marrows.getJSONObject(i));
                }
            }
            catch (JSONException e)
            {
                e.printStackTrace();
            }
        }
    }
}
